<?php
class Menu_Model_Tree extends Zen_Tree {
	
	public function __construct() {
		$table = new Zend_Db_Table ( 'menu_tree' );
		$this->table = $table;
		$types = array (
				'root' => array ('icon' => '/cms/res/icons/drive.png', 'label' => 'Блоки меню', 'valid_children' => array ('block' ), 'start_drag' => false, 'move_node' => false, 'delete_node' => false, 'remove' => false ), 
				'block' => array ('table' => 'menu_block', 'form' => 'Menu_Form_Block', 'label' => 'меню', 'view' => 'form.phtml', 'icon' => '/cms/res/icons/text_list_bullets.png', 'valid_children' => array ('link' ), 'start_drag' => true, 'move_node' => true, 'delete_node' => true, 'remove' => true ), 
				'link' => array ('table' => 'menu_link', 'form' => 'Menu_Form_Link', 'label' => 'ссылку', 'view' => 'form.phtml', 'icon' => '/cms/res/icons/link.png', 'attributes' => array ('active' => array ('1' => '/cms/res/icons/link.png', '0' => '/cms/res/icons/link_delete.png' ) ), 'valid_children' => array ('link' ), 'start_drag' => true, 'move_node' => true, 'delete_node' => true, 'remove' => true ) 
		);
		$this->setTypes ( $types );
	}
	
	public function afterCreate($id, $params) {
		if ($params ['type'] == 'block') {
			$block = new Block_Model_Blocks ();
			
			$blockData = array ('label' => $params ['label'], 'mvc_module' => 'menu', 'mvc_controller' => 'index', 'mvc_action' => 'index', 'params' => 'id/' . $id );
			$block->create ( $blockData );
		}
	}
	
	public function afterDelete($id) {
		$deleted = $this->read ( $id );
		if ($deleted == false || $deleted ['type'] != 'block')
			return false;
		$blockModel = new Block_Model_Blocks ();
		$block_table = $blockModel->getTable ();
		$par = serialize(array('id' => $id ));
		$block = $block_table->fetchRow ( "`mvc_action`='render'  and `mvc_module`='menu' and `mvc_controller`='render' and `params`='" . $par . "'" );
		if ($block) {
			$blockModel->delete ( $block ['id'] );
		}
		$blockModel->delete ( $id );
	}
	
	public function getViews() {
		$path = ROOT_PATH . "/cms/application/modules/menu/views/scripts/index/";
		$layouts = scandir ( $path );
		$res = array ();
		foreach($layouts as $layout) {
			if ((! preg_match ( '/^\./', $layout ))) {
				
				$name = preg_replace ( '/\.\S+$/', '', $layout );
				$res [$name] = $layout;
			}
		}
		return $res;
	}

}